//
// Copyright (c) 2024 BPer
//
#ifndef BPer_ALSA_DEVICE_H1
#define BPer_ALSA_DEVICE_H1
#include <bperaudiodev/BPerAudioCaptureHandle.h>
#include <bperaudiodev/BPerAudioRenderData.h>
#include <bperaudiodev/BPerAudioCapture.h>

#include <bperavutil/audio/BPerPreProcess.h>

#if BPer_OS_LINUX
#include <sys/poll.h>
#include <alsa/asoundlib.h>

struct BPerAlsaDevice {
	char *device_name;
	int32_t channels;
	int32_t period;
	snd_pcm_t *capture_handle;
	snd_pcm_t *playback_handle;
	int32_t readN, writeN;
	struct pollfd *read_fd, *write_fd;
};

class BPerAudioAecLinux: public BPerAudioCapture {
public:
	BPerAudioAecLinux(BPerAVInfo *avinfo,BPerSynBufferManager* streams);
	~BPerAudioAecLinux();

public:
	BPerAudioCaptureHandle *m_ahandle;
	int32_t init();
	void setInAudioBuffer(vector<BPerAudioPlayBuffer*> *pal);
	void setPreProcess(BPerPreProcess *pp);
	void setCatureStart();
	void setCatureStop();
    void setOutAudioBuffer(BPerAudioBuffer *pbuffer);
	void setPlayAudoBuffer(BPerAudioBuffer *pbuffer);
    void setAec(BPerRtcAec *paec);

protected:
	void run();

	void startLoop();

	void stopLoop();
	BPerAudioRenderData m_audioData;
private:

	uint8_t *m_buffer;
	BPerBool m_isInit;
	int32_t m_ret;

	BPerPreProcess *m_preProcess;

	int32_t alsa_device_open(char *device_name, uint32_t  rate,
				int32_t channels, int32_t period);
	void alsa_device_close();
	int32_t alsa_device_read(short *pcm, int32_t len);
	int32_t alsa_device_write(const short *pcm, int32_t len);
	int32_t alsa_device_capture_ready(struct pollfd *pfds, uint32_t  nfds);
	int32_t alsa_device_playback_ready(struct pollfd *pfds, uint32_t  nfds);

	int32_t alsa_device_nfds();
	void alsa_device_getfds(struct pollfd *pfds, uint32_t  nfds);

private:
	BPerAVInfo* m_avinfo;
	BPerAlsaDevice *m_dev;
	int32_t playDeviceState=1;
	int32_t catpureDeviceState = 1;
	int32_t m_size;
	BPerBool m_loops;
	int32_t m_captureChannel;
	uint32_t  m_captureSample;
	uint32_t m_sample,m_channel;
	snd_pcm_uframes_t m_captureFrames,m_frames;
	int32_t m_audioPlayCacheNum;

};

#endif
#endif
